package com.xad.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Version :1.0
 * @PROJECT_NAME: mybatis
 * @PACKAGE_NAME:com.xad.util
 * @NAME: DBUtil
 * @author:xuandian
 * @DATE: 2022/6/29 15:24
 * @description: mybatis  工具类
 */
public class DBUtil {
    private static final String resource = "mybatis.config.xml";

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //加载mybatis 配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建能执行映射文件中sql的sqlSession@ return会话提供
     * @return Mapper
     */
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}
